package com.ms.module.wechat.clear.fragment.emoji;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.entity.node.BaseNode;
import com.ms.module.wechat.clear.Details;
import com.ms.module.wechat.clear.R;
import com.ms.module.wechat.clear.base.BaseFragment;
import com.ms.module.wechat.clear.base.RxView;
import com.ms.module.wechat.clear.dialog.DialogDelete;
import com.ms.module.wechat.clear.fragment.adapter.node.FileChildNode;
import com.ms.module.wechat.clear.fragment.adapter.node.FileHeaderNode;
import com.ms.module.wechat.clear.fragment.image.ImageAdapter;
import com.ms.module.wechat.clear.internal.WeChatClearCommonn;
import com.ms.module.wechat.clear.repository.WeChatScanDataRepository;
import com.ms.module.wechat.clear.utils.ByteSizeToStringUnitUtils;
import com.ms.module.wechat.clear.utils.ListDataUtils;
import com.ms.module.wechat.clear.utils.PhotoUtils;
import com.ms.module.wechat.clear.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class EmojiFragment extends BaseFragment implements RxView.Action1<View> {

    private static EmojiFragment instance;
    private EmojiFragmentViewModel viewModel;

    public List<BaseNode> getDatas() {
        return datas;
    }

    private TextView textViewSavePhoto;
    private boolean loaderFinish = false;
    private Observer<List<BaseNode>> observerEmojiData;
    private RecyclerView recyclerView;
    private ImageAdapter adapter;
    private List<BaseNode> datas = new ArrayList<>();
    private ImageView imageViewCheck;
    private TextView textViewDelete;
    private RelativeLayout relativeLayoutTop;
    private RelativeLayout relativeLayoutNotClearProject;

    public static EmojiFragment newInstance() {
        Bundle args = new Bundle();
        EmojiFragment fragment = new EmojiFragment();
        fragment.setArguments(args);
        instance = fragment;
        return fragment;
    }

    public static EmojiFragment getInstance() {
        return instance;
    }

    @Override
    public void onAttach(@androidx.annotation.NonNull Context context) {
        super.onAttach(context);
        instance = this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_details_emoji;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        instance = this;
        viewModel = new ViewModelProvider(this).get(EmojiFragmentViewModel.class);

        adapter = new ImageAdapter();
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        adapter.setList(datas);
        recyclerView.setAdapter(adapter);

        observerEmojiData = new Observer<List<BaseNode>>() {
            @Override
            public void onChanged(List<BaseNode> baseNodes) {

                if (!loaderFinish) {
                    datas.clear();
                    datas.addAll(baseNodes);
                    adapter.setList(datas);
                    adapter.notifyDataSetChanged();
                    updateSelectAll();
                    loaderFinish = true;
                }
            }
        };

        viewModel.getLiveDataEmojiData().observe(getViewLifecycleOwner(), observerEmojiData);
        viewModel.getMutableLiveDataEmojiData().postValue(null);
    }

    public void updateSelectAll() {
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                emitter.onNext(ListDataUtils.checkAllNode(datas));
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new io.reactivex.Observer<Boolean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull Boolean check) {
                        // 更新头部全选与反选按钮
                        imageViewCheck.setSelected(check);

                        // 更新底部删除按钮 状态
                        if (check) {
                            textViewDelete.setEnabled(true);
                            textViewDelete.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_blue));
                        } else {
                            textViewDelete.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_gray));
                            textViewDelete.setEnabled(false);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


        Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Long> emitter) throws Exception {
                long filesLength = WeChatScanDataRepository.getInstance().getFilesLength(datas);
                emitter.onNext(filesLength);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new io.reactivex.Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull Long filesLength) {
                        if (filesLength == 0) {
                            textViewDelete.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_gray));
                            textViewDelete.setEnabled(false);
                            textViewDelete.setText("删除");
                            textViewSavePhoto.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_gray));
                            textViewSavePhoto.setEnabled(false);

                        } else {
                            textViewDelete.setEnabled(true);
                            textViewDelete.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_red));
                            textViewDelete.setText("删除 " + ByteSizeToStringUnitUtils.byteToStringUnit(filesLength));
                            textViewSavePhoto.setEnabled(true);
                            textViewSavePhoto.setBackground(getActivity().getResources().getDrawable(R.drawable.selector_background_color_blue));
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

        if (datas.size() == 0) {
            relativeLayoutTop.setVisibility(View.GONE);
            relativeLayoutNotClearProject.setVisibility(View.VISIBLE);
        } else {
            relativeLayoutTop.setVisibility(View.VISIBLE);
            relativeLayoutNotClearProject.setVisibility(View.GONE);
        }

    }


    @Override
    protected void initView() {
        super.initView();
        recyclerView = findViewById(R.id.recyclerView);

        imageViewCheck = findViewById(R.id.imageViewCheck);
        textViewDelete = findViewById(R.id.textViewDelete);

        relativeLayoutTop = findViewById(R.id.relativeLayoutTop);
        relativeLayoutNotClearProject = findViewById(R.id.relativeLayoutNotClearProject);
        textViewSavePhoto = findViewById(R.id.textViewSavePhoto);

        imageViewCheck.setSelected(true);

        RxView.setOnClickListeners(this::onClick, textViewDelete, textViewSavePhoto);

        imageViewCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean selected = imageViewCheck.isSelected();
                if (selected) {
                    for (int i = 0; i < datas.size(); i++) {
                        BaseNode baseNode = datas.get(i);
                        if (baseNode instanceof FileHeaderNode) {
                            FileHeaderNode headerNode = (FileHeaderNode) baseNode;
                            headerNode.setCheck(false);
                            List<BaseNode> childNode = headerNode.getChildNode();
                            for (int j = 0; j < childNode.size(); j++) {
                                BaseNode baseNode1 = childNode.get(j);
                                if (baseNode1 instanceof FileChildNode) {
                                    FileChildNode childNode1 = (FileChildNode) baseNode1;
                                    childNode1.setCheck(false);
                                }
                            }
                        }
                    }
                    imageViewCheck.setSelected(false);
                } else {

                    for (int i = 0; i < datas.size(); i++) {
                        BaseNode baseNode = datas.get(i);

                        if (baseNode instanceof FileHeaderNode) {
                            FileHeaderNode headerNode = (FileHeaderNode) baseNode;
                            headerNode.setCheck(true);
                            List<BaseNode> childNode = headerNode.getChildNode();
                            for (int j = 0; j < childNode.size(); j++) {
                                BaseNode baseNode1 = childNode.get(j);
                                if (baseNode1 instanceof FileChildNode) {
                                    FileChildNode childNode1 = (FileChildNode) baseNode1;
                                    childNode1.setCheck(true);
                                }
                            }
                        }
                    }
                    imageViewCheck.setSelected(true);
                }
                adapter.notifyDataSetChanged();
                updateSelectAll();
            }
        });
    }


    @Override
    public void onStop() {
        super.onStop();


        if (viewModel.getLiveDataEmojiData().hasObservers()) {
            viewModel.getLiveDataEmojiData().removeObserver(observerEmojiData);
        }

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.textViewDelete) {


            List<String> selectFile = WeChatScanDataRepository.getInstance().getSelectFile(datas);


            DialogDelete.show(getActivity(), "您选择了" + selectFile.size() + "张图片，删除后无法找回！", new DialogDelete.Call() {
                @Override
                public void onCancel() {
                }

                @Override
                public void onDelete() {


                    Observable.create(new ObservableOnSubscribe<Long>() {
                        @Override
                        public void subscribe(@NonNull ObservableEmitter<Long> emitter) throws Exception {
                            long filesLength = WeChatScanDataRepository.getInstance().getFilesLength(datas);
                            emitter.onNext(filesLength);

                        }
                    }).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new io.reactivex.Observer<Long>() {
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {

                                }

                                @Override
                                public void onNext(@NonNull Long filesLength) {
                                    WeChatClearCommonn.getWeChatClearCallBack().onDeleteFile(getActivity(), Details.EMOJI, filesLength);
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {

                                }

                                @Override
                                public void onComplete() {

                                }
                            });


                    WeChatScanDataRepository.getInstance().deleteFile(datas, new io.reactivex.Observer<Boolean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull Boolean aBoolean) {

                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            if (adapter != null) {
                                adapter.setList(datas);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    });
                }
            });
        } else if (view.getId() == R.id.textViewSavePhoto) {


            Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<Boolean> emitter) throws Exception {
                    List<String> selectFile = WeChatScanDataRepository.getInstance().getSelectFile(datas);
                    for (String it : selectFile) {
                        File file = new File(it);
                        PhotoUtils.saveBmp2Gallery(getContext(), BitmapFactory.decodeFile(file.getPath()), file.getName());
                    }
                    emitter.onNext(true);
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<Boolean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull Boolean s) {
                            if (s) {
                                ToastUtils.show(getContext(), "保存成功");
                            } else {
                                ToastUtils.show(getContext(), "保存失败");
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });


        }
    }
}
